#include <54func.h>
int main(int argc,char *argv[])
{
    // ./0_aqiang 192.168.187.128 1234
    ARGS_CHECK(argc,3);

    //创建套接字
    int sockfd = socket(AF_INET,SOCK_STREAM,0);

    //初始化服务器网络ip
    struct sockaddr_in serveradd;
    serveradd.sin_family = AF_INET;
    serveradd.sin_port =htons(atoi(argv[2]));//端口转换为大端序
    serveradd.sin_addr.s_addr =inet_addr(argv[1]);//主机地址转换为网络地址

    //connect：客户端向服务器段发起第一次连接，若是有回应则会发起第三次连接请求
    int ret =  connect(sockfd,(struct sockaddr *)&serveradd,sizeof(serveradd));
    ERROR_CHECK(ret,-1,"connect");


    fd_set rdset;//监听集合
    char buf[4096] = {0};
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(sockfd,&rdset);
        select(sockfd+1,&rdset,NULL,NULL,NULL);
        //select返回，说明socket or stdin就绪了，rdset现在是就绪集合
        if(FD_ISSET(STDIN_FILENO,&rdset))
        {
            //aqiang主动发消息给azhen
            bzero(buf,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            int sret = send(sockfd,buf,strlen(buf),0);//向网路socket写数据
            if(sret == 0)
            {
                //说明aqiang主动断开连接
                printf("aqiang主动断开连接！\n");
                break;
            }
        }
        if(FD_ISSET(sockfd,&rdset))
        {
            //aqiang读取azhen发来的消息
            bzero(buf,sizeof(buf));
            int sret = recv(sockfd,buf,sizeof(buf),0);//从网络socket中读取消息
            if(sret == 0)
            {
                //socket写端关闭,读端一直读取0
                printf("azhen主动断开连接!\n");
                break;
                
            }
            printf("azhen：%s\n",buf);//把阿珍发来的消息输出
        }
    }
    return 0;
}
